package cn.mall.common.relation;

import java.util.UUID;

import javax.jms.JMSException;
import javax.jms.Message;

import org.slf4j.MDC;

import com.alibaba.dubbo.rpc.RpcContext;

/**
 * 系统跟踪工具类
 */
public class RelationKit {
	
	public final static String RELATION_ID = "relation_id";
	
	public static void initRelation() {
		String relationId = generateRelationId();
		setRelationId(relationId);
	}
	
	public static void initRelationFrom(RpcContext context) {
		String relationId = (String) context.getAttachment(RELATION_ID);
		if (relationId == null) {
			relationId = generateRelationId();
		}
		setRelationId(relationId);
	}

	public static void putRelationInfo(RpcContext context) {
		String relationId = getRelationId();
		if (relationId != null) {
			context.setAttachment(RELATION_ID, relationId);
		}
	}
	
	public static void initRelationFrom(Message jmsMsg) {
		String relationId = null;
		try {
			relationId = jmsMsg.getStringProperty(RELATION_ID);
		} catch (JMSException e) {
		}
		if (relationId == null) {
			relationId = generateRelationId();
		}
		setRelationId(relationId);
	}
	
	public static void putRelationInto(Message jmsMsg) {
		String relationId = getRelationId();
		if (relationId != null) {
			try {
				jmsMsg.setStringProperty(RELATION_ID, relationId);
			} catch (JMSException e) {
			}
		}
	}
	
	public static void clearTrace() {
		MDC.remove(RELATION_ID);
	}

	public static String getRelationId() {
		return MDC.get(RELATION_ID);
	}
	
	public static void setRelationId(String relationId) {
		MDC.put(RELATION_ID, relationId);
	}

	static private String generateRelationId() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}
}
